var express = require('express');
var router = express.Router();
var PW = require('png-word');
var R = require('random-word');
var pw = new PW();
var fs = require('fs');

var users = require('./user.json');

/* GET users listing. */
// router.get('/', function(req, res, next) {
//   res.send('respond with a resource');
// });
router.post('/login', function(req, res){
  const {
    loginname,
    password,
    vnum
  }=req.body;
  if(users[loginname] && users[loginname].password === password && req.session.loginvimg == Number(vnum)){
    req.session.user = {loginname};
    res.redirect('back');
  }
});

router.get('/logout', function(req, res){
  req.session.user = null;
  res.redirect('back');
});

router.post('/register', function(req, res){
  const {
    loginname,
    password,
    confirm,
    vnum
  }=req.body;
  if(req.session.regvimg == Number(vnum) && loginname && password && password === confirm){
    users[loginname] = {loginname, password};
    fs.writeFileSync(__dirname+"/user.json", JSON.stringify(users));
    res.redirect('back');
  }
});

router.get('/loginvimg', function(req, res){
  var r = new R("0123456789");
  req.session.loginvimg = r.random(5);
  pw.createReadStream(req.session.loginvimg).pipe(res);
});

router.get('/regvimg', function(req, res){
  var r = new R("0123456789");
  req.session.regvimg = r.random(5);
  pw.createReadStream(req.session.regvimg).pipe(res);
});

router.get('/commentvimg', function(req, res){
  var r = new R("0123456789");
  req.session.commentvimg = r.random(5);
  pw.createReadStream(req.session.commentvimg).pipe(res);
});


var messages = require('./message.json');
router.post('/sendmsg', function(req, res){
  const {
    messagetext,
    vnum
  }= req.body;
  if(req.session.commentvimg == Number(vnum) && messagetext){
    const message = {
      username:req.session.user,
      text:messagetext
    };
    messages.push(message);
    fs.writeFileSync(__dirname+"/message.json", JSON.stringify(messages));
    res.redirect('back');
  }
});

module.exports = router;
